using FileMapper;
using System;
using System.IO;

namespace FileMapper.Tests {
    public class FilterPlugin: FormatPlugin {
        public delegate bool Condition(byte b);

        protected Condition condition;

        public FilterPlugin(Condition condition) {
            this.condition = condition;
        }

        protected override ExtentList GetFixedExtents(Stream file) {
            var position = file.Position;
            try {
                file.Position = 0;
                var result = new ExtentList();
                bool fixExt = false;
                byte[] buffer = new byte[1];
                long offset = 0;
                long size = 0;
                long start = 0;
                while (0 < file.Read(buffer, 0, 1)) {
                    if (fixExt) {
                        if (condition(buffer[0])) {
                            ++size;
                        } else {
                            fixExt = false;
                            result.Add(new Extent { Offset = start, Size = size });
                            size = 0;
                        }
                    } else {
                        if (condition(buffer[0])) {
                            fixExt = true;
                            start = offset;
                            ++size;
                        }
                    }
                    ++offset;
                }
                if (0 < size) {
                    result.Add(new Extent { Offset = start, Size = size });
                }
                return result;
            } finally {
                file.Position = position;
            }
        }

    }
}
